package com.feidee.bigdata.bloomfilterserv.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feidee.bigdata.bloomfilterserv.constant.Constant;
import com.feidee.bigdata.bloomfilterserv.dao.impl.BloomFilterDaoImpl;
import com.feidee.bigdata.bloomfilterserv.model.CalcResultModel;
import com.feidee.bigdata.bloomfilterserv.model.RequestParamModel;
import com.feidee.bigdata.bloomfilterserv.service.IBloomFilterServService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class BloomFilterServController {

	private Logger logger = LoggerFactory.getLogger(BloomFilterServController.class);

	@Resource(shareable = true)
	private IBloomFilterServService bloomFilterServService;

	@RequestMapping(value = "blserv")
	public CalcResultModel exclusiveFilterCalc(@RequestParam String data) {

		RequestParamModel requestParamModel = JSON.parseObject(data, RequestParamModel.class);
		CalcResultModel resultModel = bloomFilterServService.exclusiveCalc(requestParamModel);

		if (Constant.LOG_PRINT_CNT % Constant.LOG_PRINT_FREQUENCY == 0) {
			logger.info("BloomFilter Result:" + JSON.toJSONString(resultModel));
		}
		Constant.LOG_PRINT_CNT += 1;

		return resultModel;

	}

	@RequestMapping(value = "blservStatus")
	public String blservStatus(@RequestParam String type) {

		if ("1".equals(type)) {
			JSONObject statusObject = new JSONObject();
			statusObject.put("ipFlag", Constant.UUID_IP_PREFIX);
			statusObject.put("logPrintCnt", Constant.LOG_PRINT_CNT);

			return statusObject.toJSONString();
		} else if ("2".equals(type)) {
			new BloomFilterDaoImpl().clearBF();

			return "clear bloomfilter success!!!";
		} else if (type.length() >= 4) {
			return String.valueOf(BloomFilterDaoImpl.bloomFilter.mightContain(type));
		} else {

			return "PONG";
		}

	}

}
